package com.example.qqviewspringboot.service;

import com.example.qqviewspringboot.controller.FriendshipController;
import com.example.qqviewspringboot.data.Friendship;
import com.example.qqviewspringboot.data.Notification;
import com.example.qqviewspringboot.data.User;
import com.example.qqviewspringboot.dto.FriendDTO;
import com.example.qqviewspringboot.repository.FriendshipRepository;
import com.example.qqviewspringboot.repository.NotificationRepository;
import com.example.qqviewspringboot.repository.UserRepository;
import com.example.qqviewspringboot.security.CustomUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.core.Authentication;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class FriendshipService {

    @Autowired
    private FriendshipRepository friendshipRepository;

    @Autowired
    private NotificationRepository notificationRepository;

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private NotificationService notificationService; // 注入 NotificationService
    private static final Logger log = LoggerFactory.getLogger(FriendshipController.class);

    // 创建通知
    private void createNotification(Long recipientId, String message, String type) {
        if (recipientId == null || message == null || message.trim().isEmpty()) {
            throw new IllegalArgumentException("Recipient ID and message cannot be null or empty");
        }

        // 确保 recipientId 对应的 User 存在
        Optional<User> recipient = userRepository.findById(recipientId);
        if (!recipient.isPresent()) {
            log.error("Recipient with ID {} not found. Notification not created.", recipientId);
            throw new IllegalArgumentException("Recipient not found");
        }

        Notification notification = new Notification();
        notification.setRecipientId(recipientId);
        notification.setMessage(message);
        notification.setType(type);
        notification.setIsRead(false);
        notificationRepository.save(notification);

        log.info("Notification created successfully for userId {}: {}", recipientId, message);
    }



    // 添加好友请求

    @Transactional
    public void addFriend(Long senderId, Long receiverId) {
        // 检查是否已经存在好友关系或请求
        Optional<Friendship> existingFriendship = friendshipRepository.findByUserIdAndFriendId(senderId, receiverId);
        if (existingFriendship.isPresent()) {
            throw new IllegalStateException("Friendship already exists or is pending");
        }

        // 创建好友请求
        Friendship friendship = new Friendship();
        friendship.setUserId(senderId); // 发起请求的用户
        friendship.setFriendId(receiverId); // 接收请求的用户
        friendship.setStatus(Friendship.Status.PENDING);
        friendshipRepository.save(friendship);

        // 通知接收者
        createNotification(receiverId, "You have a new friend request from user " + senderId, "FRIEND_REQUEST");

    }

    // 获取好友列表
    public List<FriendDTO> getFriends(Long userId) {
        List<Friendship> friendships = friendshipRepository.findByUserIdOrFriendIdAndStatus(userId, Friendship.Status.ACCEPTED);

        return friendships.stream()
                .map(friendship -> {
                    Long friendId = (friendship.getUserId().equals(userId)) ? friendship.getFriendId() : friendship.getUserId();
                    User user = userRepository.findById(friendId).orElse(null);
                    return user != null ? new FriendDTO(user.getId(), user.getUsername(), user.getAvatarUri()) : null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }




    // 接受好友请求

    public void acceptFriendRequest(Long userId, Long friendId) {
        // 查找单向或双向的好友请求
        Optional<Friendship> friendship = friendshipRepository.findPendingFriendship(userId, friendId);

        if (friendship.isPresent()) {
            Friendship existingFriendship = friendship.get();

            // 更新好友请求状态为 ACCEPTED
            existingFriendship.setStatus(Friendship.Status.ACCEPTED);
            friendshipRepository.save(existingFriendship);

            // 检查并创建反向好友关系（如果不存在）
            Optional<Friendship> reverseFriendship = friendshipRepository.findByUserIdAndFriendId(friendId, userId);
            if (!reverseFriendship.isPresent()) {
                Friendship reverse = new Friendship();
                reverse.setUserId(friendId);
                reverse.setFriendId(userId);
                reverse.setStatus(Friendship.Status.ACCEPTED);
                friendshipRepository.save(reverse);
            } else if (reverseFriendship.get().getStatus() != Friendship.Status.ACCEPTED) {
                // 如果反向关系存在但状态不是 ACCEPTED，更新状态
                Friendship existingReverseFriendship = reverseFriendship.get();
                existingReverseFriendship.setStatus(Friendship.Status.ACCEPTED);
                friendshipRepository.save(existingReverseFriendship);
            }

            // 发送通知给发起人
            notificationService.createNotification(friendId, "Your friend request to user " + userId + " has been accepted.", "FRIEND_REQUEST_ACCEPTED");

            log.info("Friend request accepted between userId={} and friendId={}", userId, friendId);
        } else {
            log.warn("No pending friend request found for userId={} and friendId={}", userId, friendId);
            throw new IllegalArgumentException("Friend request not found or already processed.");
        }
    }



    // 拒绝好友请求
    public void rejectFriendRequest(Long userId, Long friendId) {
        Optional<Friendship> friendship = friendshipRepository.findByUserIdAndFriendId(userId, friendId);

        if (friendship.isPresent() && friendship.get().getStatus() == Friendship.Status.PENDING) {
            friendshipRepository.delete(friendship.get()); // 删除好友请求

            // 通知发送者好友请求被拒绝
            notificationService.createNotification(friendId, "Your friend request to user " + userId + " has been rejected.", "FRIEND_REQUEST_REJECTED");

            log.info("Friend request rejected between userId={} and friendId={}", userId, friendId);
        } else {
            log.warn("No pending friend request found for userId={} and friendId={}", userId, friendId);
            throw new IllegalArgumentException("Friend request not found or already processed.");
        }
    }


    // 获取好友关系状态
    public String getFriendshipStatus(Long userId, Long friendId) {
        // 确保 userId 始终小于 friendId，保持查询唯一性
        if (userId > friendId) {
            Long temp = userId;
            userId = friendId;
            friendId = temp;
        }

        // 查询好友关系
        Optional<Friendship> friendship = friendshipRepository.findByUserIdAndFriendId(userId, friendId);

        // 返回状态
        return friendship.map(f -> f.getStatus().name()).orElse("NO_RELATION");
    }


    // 获取待处理的好友请求列表
    public List<User> getPendingRequests(Long userId) {
        try {
            List<Friendship> pendingRequests = friendshipRepository.findByFriendIdAndStatus(userId, Friendship.Status.PENDING);
            return pendingRequests.stream()
                    .map(request -> userRepository.findById(request.getUserId()).orElse(null))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("Error fetching pending requests for userId={}: {}", userId, e.getMessage(), e);
            throw new RuntimeException("Failed to fetch pending friend requests. Please try again later.");
        }
    }


}
